/*
 * All rights Reserved, Designed By DataDriver
 * Copyright:    DataDriver.Inc
 * Company:      Zhuo Wo Infomation Technology (ShangHai) CO.LTD
 */
package com.sun.register;

import com.sun.bean.MyBean;
import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 在Spring中除了@Service等相关注解将我们的bean注入的IOC容器中
 * 也可以通过编程式的方式实现Bean的注册到IOC容器中
 * <p>
 * <p>
 * BeanDefinitionRegistryPostProcessor继承BeanFactoryPostProcessor
 */

@Component
public class MyBeanDefinitionRegister implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        //创建Bean定义类的对象，将MyBean的对象注入到IOC容器中

        /**
         * RootBeanDefinition--继承->AbstractBeanDefinition--实现->BeanDefinition
         */
        RootBeanDefinition beanDefinition = new RootBeanDefinition(MyBean.class);
        //bean的定义注入到Spring环境中(myBean是在IOC容器中的bean的ID)
        beanDefinitionRegistry.registerBeanDefinition("myBean222", beanDefinition);
    }

    @SneakyThrows
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        BeanDefinition myBean222 = configurableListableBeanFactory.getBeanDefinition("myBean222");
        System.out.println("根据bean的名称获取当前的bean对象:" + myBean222.getBeanClassName());
    }
}
